'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const logger = require('../../common/logutility').logger('optExpLst');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        let expCouTel = req.session.userTel;
        let exps = yield dbutility.expModel.getExpNeedDlv(expCouTel);
        res.render('./cou/optExpLst', { rows: exps });
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        let expNo = req.body.selectedItem;
        let expCouTel = req.session.userTel;
        let exp = yield dbutility.expModel.getExp(expNo, expCouTel);
        req.session.expOpt = exp;
        if (exp) {
            if (req.body.cmdType === 'L') {
                req.session.expUpd = exp;
                res.redirect('/updExpInp');
            } else if (req.body.cmdType === 'R') {
                req.session.expDel = exp;
                res.redirect('/delExpConf');
            }
        } else {
            res.redirect('/error');
        }
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;